package com.rockcent.helper;

import com.rockcent.common.common.BusinessException;
import com.rockcent.mall.lib.dto.AuthResourceDto;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created by zhangjh on 2017/3/20.
 */
public enum AuthResourceHelper {
    SINGLETON;

    /**
     * 递归查找子节点,并排序
     *
     * @param sour
     * @param allList
     * @return
     */
    public List<AuthResourceDto> createTree(AuthResourceDto sour, List<AuthResourceDto> allList) {
        Long id = sour == null ? null : sour.getId();
        List<AuthResourceDto> childs = allList.stream().filter(bean -> Objects.equals(bean.getParentId(), id)).sorted(Comparator.comparingLong(AuthResourceDto::getSort)).collect(Collectors.toList());
        if (null != childs && !childs.isEmpty()) {
            for (AuthResourceDto child : childs) {
                child.setAuthResourceList(createTree(child, allList));
            }
        }
        return childs;
    }

    public void isHaveThreeLevelNode(List<AuthResourceDto> topList) {
        if (null == topList || 0 == topList.size()) {
            throw new BusinessException("必须选中三级菜单");
        }
        boolean isHaveThreeLevelNodeFlag = true;
        for (AuthResourceDto topAuthResource : topList) {
            List<AuthResourceDto> secondLevelAuthResourceList = topAuthResource.getAuthResourceList();
            if (null == secondLevelAuthResourceList || 0 == secondLevelAuthResourceList.size()) {
                isHaveThreeLevelNodeFlag = false;
                throw new BusinessException("必须选中三级菜单");
            } else {
                for (AuthResourceDto secondAuthResource : secondLevelAuthResourceList) {
                    List<AuthResourceDto> threeLevelAuthResourceList = secondAuthResource.getAuthResourceList();
                    if (null == threeLevelAuthResourceList || 0 == threeLevelAuthResourceList.size()) {
                        throw new BusinessException("必须选中三级菜单");
                    }

                }
            }

        }

    }


    public void validateIsHave( List<AuthResourceDto> authResourceList){
        List<AuthResourceDto> topList = AuthResourceHelper.SINGLETON.createTree(null,authResourceList);
        isHaveThreeLevelNode(topList);
    }
}